package com.acooly.module.openapi.client.provider.allinpay.signature;

import com.acooly.module.openapi.client.provider.allinpay.AllinpayConstants;
import com.acooly.module.safety.exception.SignatureVerifyException;
import com.acooly.module.safety.signature.Signer;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Component;

import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author zhike 2017/11/28 11:41
 */
@Component("safetyAllinpayMd5Signer")
public class AllinpayMd5Signer implements Signer<Map<String, String>, String> {

    @Override
    public String sign(Map<String, String> plain, String key) {
        String waitToSignStr = getWaitToSigin(plain,key);
        // MD5摘要签名计算
        return DigestUtils.md5Hex(waitToSignStr);
    }

    @Override
    public void verify(Map<String, String> plain, String key, String verifySign) {
        String waitToSignStr = getWaitToSigin(plain,key);
        // MD5摘要签名计算
        String signature = DigestUtils.md5Hex(waitToSignStr);
        if (!verifySign.equalsIgnoreCase(signature)) {
            throw new SignatureVerifyException("验签未通过");
        }
    }

    protected String getWaitToSigin(Map<String, String> plain,String key) {
        String waitToSignStr = null;
        plain.put("key", key);//将分配的appkey加入排序
        Map<String, String> sortedMap = new TreeMap(plain);
        if (sortedMap.containsKey("sign")) {
            sortedMap.remove("sign");
        }

        StringBuilder stringToSign = new StringBuilder();
        if (sortedMap.size() > 0) {
            Iterator var5 = sortedMap.entrySet().iterator();

            while (var5.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry) var5.next();
                if (entry.getValue() != null) {
                    stringToSign.append((String) entry.getKey()).append("=").append((String) entry.getValue()).append("&");
                }
            }

            stringToSign.deleteCharAt(stringToSign.length() - 1);
            waitToSignStr = stringToSign.toString();
        }

        return waitToSignStr;
    }

    @Override
    public String getSinType() {
        return AllinpayConstants.MD5_SIGNER_TYPE;
    }
}




